package com.hnucm.c202001020216.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.hnucm.c202001020216.DataApplication;
import com.hnucm.c202001020216.R;
import com.hnucm.c202001020216.api.CommentApi;
import com.hnucm.c202001020216.databinding.ActivityLookCarBinding;
import com.hnucm.c202001020216.databinding.CarCommentItemBinding;
import com.hnucm.c202001020216.pojo.Car;
import com.hnucm.c202001020216.pojo.Comment;
import com.hnucm.c202001020216.utils.RetrofitUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LookCarActivity extends AppCompatActivity {

    public final String TAG = "LookCarActivity";
    ActivityLookCarBinding lookCarBinding;

    public List<Comment.UserCommentListDTO> userCommentList = new ArrayList<>();
    RecyclerView recyclerView;
    ImageView shareBtn;
    MyAdapter myAdapter = new MyAdapter();
    ImageView returnBtn;
    Car.PageDTO.ListDTO keyCar = new Car.PageDTO.ListDTO();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: ");
        super.onCreate(savedInstanceState);
        lookCarBinding = DataBindingUtil.setContentView(this, R.layout.activity_look_car);

        ImmersionBar.with(this)
                .transparentStatusBar()
                .statusBarDarkFont(true)
                .init();

        //获取上个界面的数据
        //从chooseFragment跳转过来
        keyCar = (Car.PageDTO.ListDTO) getIntent().getSerializableExtra("keyCar");
        if (keyCar == null) {
            keyCar = (Car.PageDTO.ListDTO) getIntent().getSerializableExtra("Share_keyCar");
        }
        lookCarBinding.textView39.setText(keyCar.carName);
        lookCarBinding.textView41.setText(keyCar.carPrice + "");
        ImageView imageViewLogo = lookCarBinding.imageView22;
        recyclerView = lookCarBinding.recyclerView;
        shareBtn = lookCarBinding.shareBtn;
        returnBtn = lookCarBinding.imageView19;


        Glide.with(this)
                .load(keyCar.carPic)
                .into(imageViewLogo);
        //通过汽车的编号获取用户评论
        CommentApi api = RetrofitUtils.getRetrofit(DataApplication.HttpURL).create(CommentApi.class);
        Call<Comment> call = api.findByCarId(keyCar.id);
        call.enqueue(new Callback<Comment>() {
            @Override
            public void onResponse(Call<Comment> call, Response<Comment> response) {
                userCommentList = response.body().userCommentList;
                if (userCommentList == null) {

                }
                recyclerView.setAdapter(myAdapter);
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<Comment> call, Throwable t) {

            }
        });
        //share按钮监听
        shareBtn.setOnClickListener(
                (view) -> {
                    Intent intent = new Intent(LookCarActivity.this, ShareActivity.class);
                    intent.putExtra("keyCar", keyCar);
                    startActivity(intent);
                }
        );
        //返回到chooseFragment
        returnBtn.setOnClickListener(
                (view) -> {
                    finish();
                }
        );
        recyclerView.setLayoutManager(new LinearLayoutManager(LookCarActivity.this));
    }

    //activity重新可见时刷新数据
    @Override
    protected void onRestart() {
        Log.d(TAG, "onRestart: ");
        CommentApi api = RetrofitUtils.getRetrofit(DataApplication.HttpURL).create(CommentApi.class);
        Call<Comment> call = api.findByCarId(keyCar.id);
        call.enqueue(new Callback<Comment>() {
            @Override
            public void onResponse(Call<Comment> call, Response<Comment> response) {
                userCommentList = response.body().userCommentList;
                if (userCommentList == null) {

                }
                recyclerView.setAdapter(myAdapter);
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<Comment> call, Throwable t) {

            }
        });
        super.onRestart();
    }

    //评论数据适配器
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            CarCommentItemBinding carCommentItemBinding = DataBindingUtil.inflate(LayoutInflater.from(LookCarActivity.this)
                    , R.layout.car_comment_item, parent, false);
            MyViewHolder myViewHolder = new MyViewHolder(carCommentItemBinding.getRoot());
            myViewHolder.commentItemBinding = carCommentItemBinding;
            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.commentItemBinding.setComment(userCommentList.get(position));
            holder.commentItemBinding.imageView24.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    //修改评论接口
                    Comment.UserCommentListDTO comment = new Comment.UserCommentListDTO();
                    comment.id = userCommentList.get(position).id;
                    comment.carId = userCommentList.get(position).carId;
                    comment.userId = userCommentList.get(position).userId;
                    comment.userName = userCommentList.get(position).userName;
                    comment.commentPic = userCommentList.get(position).commentPic;
                    comment.commentContent = userCommentList.get(position).commentContent;
                    comment.commentLike = userCommentList.get(position).commentLike + 1;
                    comment.commentCollect = userCommentList.get(position).commentCollect;
                    //暂时修改UI，等下次进入这个界面再请求新数据，减少带宽
                    holder.commentItemBinding.textView48.setText((userCommentList.get(position).commentLike + 1) + "");
                    String dataBody = new Gson().toJson(comment);
                    CommentApi api = RetrofitUtils.getRetrofit(DataApplication.HttpURL).create(CommentApi.class);
                    RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), dataBody);
                    Call<com.hnucm.c202001020216.pojo.Response> call = api.updateComment(body);
                    call.enqueue(new Callback<com.hnucm.c202001020216.pojo.Response>() {
                        @Override
                        public void onResponse(Call<com.hnucm.c202001020216.pojo.Response> call, Response<com.hnucm.c202001020216.pojo.Response> response) {
                            assert response.body() != null;
                            if (response.body().msg.equals("success")) {
                                Toast.makeText(LookCarActivity.this, "点赞成功", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<com.hnucm.c202001020216.pojo.Response> call, Throwable t) {

                        }
                    });
                }
            });
        }

        @Override
        public int getItemCount() {
            return userCommentList.size();
        }
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        CarCommentItemBinding commentItemBinding;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}